
const md5 = require('md5');
import register from 'register/';
const ajax = register.plugins
// console.log(register);

 const Image = {
  // 把blob转化成url
  getObjectURL: (file) => {
    var url = null;
    if (window.createObjectURL !== undefined) {
      url = window.createObjectURL(file);
    } else if (window.URL !== undefined) {
      url = window.URL.createObjectURL(file);
    } else if (window.webkitURL !== undefined) {
      url = window.webkitURL.createObjectURL(file);
    }
    return url;
  },
  /**
   * 得到阿里云oss认证签名
   */
  getSignature: (callback) => {
    // 之前已经取过oss认证签名,并且没有过期,则直接使用
    if (Image.cachedSignature &&
      Date.now() < (Image.cachedSignature.expire - 10) * 1000) {
      if (typeof callback === 'function') {
        callback(Image.cachedSignature);
      }
    } else {
      console.log('this~', this);
      ajax.api_global_ossSign({
        noLoading: true,
        succFn: res => {
          console.log(res);

          if (res && res.OSSAccessKeyId != null) {
            Image.cachedSignature = res;
            if (jQuery.isFunction(callback)) callback(res);
          } else {
            console.error('getSignature error');
          }
        }
      })
      // getOSSSignature()
      //   .then((response) => {
      //     const data = response.data;
      //     if (data && data.OSSAccessKeyId != null) {
      //       Image.cachedSignature = data;
      //       if ($.isFunction(callback)) callback(data);
      //     } else {
      //       console.error('getSignature error');
      //     }
      //   })
      //   .catch(err => console.log(err));
    }
  },
  /**
   * 上传到阿里云oss
   * @param {blob} [blob] [图片二进制文件]
   * @param {string} [name] [上传到cdn的图片名称]
   * @param {function} [callback] [回调]
   */
  uploadImg: (blob, name, callback, progress) => {

    Image.getSignature((signature) => {
      console.log(signature);
      const fd = new FormData();
      fd.append('policy', signature.policy);
      fd.append('OSSAccessKeyId', signature.OSSAccessKeyId);
      fd.append('Signature', signature.Signature);
      fd.append('key', name);
      fd.append('file', blob);
      fd.append('success_action_status', 200);

      var params = {
        url: signature.host,
        type: 'POST',
        data: fd,
        processData: false,
        contentType: false,
        complete: function () {
          // if ($.isFunction(callback)) callback('complete');
        },
        success: function () {
          console.log('uploadImg success');
          if (jQuery.isFunction(callback)) callback('success');
        },
        error: function ($xhr, status, error) {
          console.error('uploadImg error', arguments);
          if (jQuery.isFunction(callback)) callback('error', error);
        },
        //
        xhr: function () {
          // get the native XmlHttpRequest object
          var xhr = jQuery.ajaxSettings.xhr();
          // set the onprogress event handler
          xhr.upload.onprogress = function(event) {
            if (jQuery.isFunction(progress)) {
              progress(event, name);
            }
          };
          // set the onload event handler
          xhr.upload.onload = function () {
            console.log('image uploaded');
          };
          // return the customized object
          return xhr;
        }
      };

      jQuery.ajax(params);
    });
  },

  // Base64格式转换为二进制格式
  base64ToBlob: function (dataurl) {
    dataurl = dataurl.split(',');
    if (dataurl.length > 1) {
      dataurl = dataurl[1];
    }
    // 抽取DataURL中的数据部分，从Base64格式转换为二进制格式
    var bin = atob(dataurl.toString());
    // 创建空的Uint8Array
    var buffer = new Uint8Array(bin.length);
    // 将图像数据逐字节放入Uint8Array中
    for (var i = 0; i < bin.length; i++) {
      buffer[i] = bin.charCodeAt(i);
    }

    var blob = new Blob([buffer.buffer], {type: 'image/jpeg'});

    return blob;
  },

  // blob转base64
  blobToBase64: function (blob, callback) {
    var reader = new window.FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = function() {
      var base64data = reader.result;
      if (jQuery.isFunction(callback)) callback(base64data);
    };
  },

  /**
   * 得到图片的cdn名称
   * @param  {[type]} src    [图片源地址]
   * @param  {[type]} width  [图片宽度]
   * @param  {[type]} height [图片高度]
   * @param  {[type]} size   [图片尺寸]
   * @param  {[type]} type   [图片的mimetype]
   */
  getCDNName: (src, width, height, size, type) => {
    const isGif = (type === 'image/gif');
    return md5(src + '_' + size) + '_W' + width + '_H' + height + '_G' + (isGif ? 1 : 0);
  },
};
export default Image ;

